package com.iamteer.cupband;


import android.app.ActionBar;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

    static Activity mainActivity;
    static int resultBack = 0;
    static int waterLeft = 90;
    static int result;
    static int Goal;
    static final String KEY_Goal = "keyGoal";
    static final String KEY_result = "keyResult";
    static final String KEY_waterLeft = "keyWaterLeft";
    static final String KEY_cupBondingEnable = "keyCupBondingEnable";
    static final String KEY_goalSettingEnable = "keyGoalSettingEnable";
    static final String SharedPreferencesName = "CupBandSharedPreferences";

    public static final String TAG = "CupBand";
    public static final int REQUEST_SELECT_DEVICE = 1;
    public static final int REQUEST_ENABLE_BT = 2;
    public static final int GET_CORRECT_DEVICE = 1;
    public static final int UART_PROFILE_CONNECTED = 20;
    public static final int UART_PROFILE_DISCONNECTED = 21;

//    public static final String DEGREE = "°";

    public final static int OBSERVE = 0;
    public final static int HISTORY = 1;

    public static boolean cupBondingEnable;
    public static boolean goalSettingEnable;
    public static int fragmentIndicator = OBSERVE;
    public static int mState = UART_PROFILE_DISCONNECTED;


    private Button btnRemoteInteract;
    private Button btnSetGoal;
    private Button btnBonding;

    private RelativeLayout observeLayout;
    private RelativeLayout historyLayout;
    private TextView tvObserveBottom;
    private TextView tvHistoryBottom;

    public static UartService mService = null;
    public static BluetoothDevice mDevice = null;
    public static BluetoothAdapter mBtAdapter = null;

    SharedPreferences sharedPreferences;
//    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainActivity = this;

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowHomeEnabled(true);
        ActionBar.LayoutParams lp = new ActionBar.LayoutParams(
                ActionBar.LayoutParams.MATCH_PARENT,
                ActionBar.LayoutParams.MATCH_PARENT,
                Gravity.LEFT);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View titleView = inflater.inflate(R.layout.activity_main_title, null);
        actionBar.setCustomView(titleView, lp);

        actionBar.setDisplayShowHomeEnabled(false);//去掉导航
        actionBar.setDisplayShowTitleEnabled(false);//去掉标题
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);

        observeLayout = (RelativeLayout) titleView.findViewById(R.id.observeLayout);
        historyLayout = (RelativeLayout) titleView.findViewById(R.id.historyLayout);
        tvObserveBottom = (TextView) titleView.findViewById(R.id.tvObserveBottom);
        tvHistoryBottom = (TextView) titleView.findViewById(R.id.tvHistoryBottom);

        btnRemoteInteract = (Button) findViewById(R.id.btnRemoteInteract);
        btnSetGoal = (Button) findViewById(R.id.btnSetGoal);
        btnBonding = (Button) findViewById(R.id.btnBonding);


        FragmentIndicatorChange();

        observeLayout.setOnClickListener(new OnClickListener());
        historyLayout.setOnClickListener(new OnClickListener());

        btnRemoteInteract.setOnClickListener(new OnClickListener());
        btnSetGoal.setOnClickListener(new OnClickListener());
        btnBonding.setOnClickListener(new OnClickListener());

//        int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
//        Log.d(TAG, "Max memory is " + maxMemory + "KB");

        sharedPreferences = getSharedPreferences(SharedPreferencesName, Activity.MODE_PRIVATE);
//        editor = sharedPreferences.edit();

        cupBondingEnable = sharedPreferences.getBoolean(KEY_cupBondingEnable, false);
        goalSettingEnable = sharedPreferences.getBoolean(KEY_goalSettingEnable, false);
        Goal = sharedPreferences.getInt(KEY_Goal, 8);
        result = sharedPreferences.getInt(KEY_result, 4);
        waterLeft = sharedPreferences.getInt(KEY_waterLeft, 10);
    }


    private class OnClickListener implements View.OnClickListener {
        public void onClick(View view) {

            switch (view.getId()) {

                case R.id.btnRemoteInteract:
                    RemoteInteract();
                    break;

                case R.id.btnSetGoal:
                    GoalSetting();
                    break;

                case R.id.btnBonding:
                    Bonding();
                    break;

                case R.id.observeLayout:
                    if (fragmentIndicator == HISTORY) {
                        fragmentIndicator = OBSERVE;
                        FragmentIndicatorChange();
                    }
                    break;

                case R.id.historyLayout:
                    if (fragmentIndicator == OBSERVE) {
                        fragmentIndicator = HISTORY;
                        FragmentIndicatorChange();
                    }
            }
        }
    }

    private void GoalSetting() {
        Intent intent = new Intent(MainActivity.this, GoalSettingActivity.class);
        startActivity(intent);
    }

    private void RemoteInteract() {
        Intent intent = new Intent(MainActivity.this, RemoteInteractActivity.class);
        startActivity(intent);
    }

    private void Bonding() {
        Intent intent = new Intent(MainActivity.this, BondingActivity.class);
        startActivity(intent);
//        startActivityForResult(intent, GET_CORRECT_DEVICE);
    }

    private void FragmentIndicatorChange() {
        if (fragmentIndicator == OBSERVE) {
            tvObserveBottom.setBackgroundColor(Color.parseColor("#FFFFFF"));
            tvHistoryBottom.setBackgroundColor(Color.parseColor("#6BB6EA"));
            getFragmentManager().beginTransaction()
                    .replace(R.id.mainFragment, new ObserveFragment())
                    .commit();
        } else {
            tvObserveBottom.setBackgroundColor(Color.parseColor("#6BB6EA"));
            tvHistoryBottom.setBackgroundColor(Color.parseColor("#FFFFFF"));
            getFragmentManager().beginTransaction()
                    .replace(R.id.mainFragment, new HistoryFragment())
                    .commit();
        }
    }
///*    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        try {
//            LocalBroadcastManager.getInstance(this).unregisterReceiver(UARTStatusChangeReceiver);
//        } catch (Exception ignore) {
//            Log.e(TAG, ignore.toString());
//        }
//        unbindService(mServiceConnection);
//        mService.stopSelf();
//        mService= null;
//    }*/
///*
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
//        Log.i(TAG, "Get Result: " + requestCode + "    " + resultCode + "   " + data);
//        switch (requestCode) {
//            //获得正确地址，准备连接
//            case GET_CORRECT_DEVICE:
//                if (resultCode == Activity.RESULT_FIRST_USER) {
//                    serviceInit();
//                    String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
//                    mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);
//                    Log.i(TAG, "Device Address: " + mDevice);
//                    mService.connect(deviceAddress);
//                }
//                break;
//        }
//    }
//
//
//    private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
//        public void onReceive(Context context, Intent intent) {
//            String action = intent.getAction();
//
//            final Intent mIntent = intent;
//            /*//*********************//*/
//            if (action.equals(UartService.ACTION_GATT_CONNECTED)) {
//                runOnUiThread(new Runnable() {
//                    public void run() {
//                        Log.d(MainActivity.TAG, "UART_CONNECT_MSG");
//                        MainActivity.mState = MainActivity.UART_PROFILE_CONNECTED;
//                    }
//                });
//            }
//
//            /*//*********************//*/
//            if (action.equals(UartService.ACTION_GATT_DISCONNECTED)) {
//                runOnUiThread(new Runnable() {
//                    public void run() {
//                        Log.d(MainActivity.TAG, "UART_DISCONNECT_MSG");
//                        MainActivity.mState = MainActivity.UART_PROFILE_DISCONNECTED;
//                        MainActivity.mService.close();
//                    }
//                });
//            }
//
//            /*//*********************//*/
//            if (action.equals(UartService.ACTION_GATT_SERVICES_DISCOVERED)) {
//                MainActivity.mService.enableTXNotification();
//            }
//            /*//*********************//*/
//            if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {
//                final byte[] rxByte = intent.getByteArrayExtra(UartService.EXTRA_DATA);
//                String hexString = "";
//                for(int i=0;i<rxByte.length;i++){
//                    hexString += Integer.toHexString((rxByte[i] & 0x000000FF) | 0xFFFFFF00).substring(6).toUpperCase();
//                    hexString += " ";
//                }
//                Log.i(MainActivity.TAG, hexString);
//            }
//            /*//*********************//*/
//            if (action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_UART)) {
//                Log.i(MainActivity.TAG,"Device doesn't support UART. Disconnecting");
//                MainActivity.mService.disconnect();
//            }
//        }
//    };
//
//
//    private ServiceConnection mServiceConnection = new ServiceConnection() {
//        @Override
//        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
//            MainActivity.mService = ((UartService.LocalBinder) rawBinder).getService();
//            Log.d(MainActivity.TAG, "onServiceConnected mService = " + MainActivity.mService);
//            if(!MainActivity.mService.initialize()){
//                Log.e(MainActivity.TAG, "Unable to initialize Bluetooth");
//                finish();
//            }
//        }
//
//        @Override
//        public void onServiceDisconnected(ComponentName name) {
//            MainActivity.mService = null;
//        }
//    };
//
//    private void serviceInit() {
//        Intent bindIntent = new Intent(this, UartService.class);
//        bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
//        LocalBroadcastManager.getInstance(this).registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
//    }
//
//    private static IntentFilter makeGattUpdateIntentFilter() {
//        final IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction(UartService.ACTION_GATT_CONNECTED);
//        intentFilter.addAction(UartService.ACTION_GATT_DISCONNECTED);
//        intentFilter.addAction(UartService.ACTION_GATT_SERVICES_DISCOVERED);
//        intentFilter.addAction(UartService.ACTION_DATA_AVAILABLE);
//        intentFilter.addAction(UartService.DEVICE_DOES_NOT_SUPPORT_UART);
//        return intentFilter;
//    }*/
}
